<template>
  <el-row>
    <el-col :span="3" style="margin-bottom: 8px">
      <p class="pinformation">搜索条件</p>
    </el-col>
  </el-row>
  <el-form
    :model="queryParams"
    label-width="120px"
    ref="groupJcxmGroupRef"
    @submit.native.prevent
  >
    <el-row>
      <el-col :span="13">
        <el-form-item label="检测项目组别：" prop="groupName">
          <el-input
            clearable
            v-model="queryParams.groupName"
            maxlength="100"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="检测方法：" prop="methodName">
          <el-input
            clearable
            v-model="queryParams.methodName"
            maxlength="100"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
      </el-col>
      <el-col :span="5">
        <el-form-item label-width="20px">
          <el-button type="success" @click="handleQuery()">搜索</el-button>
          <el-button class="business resetBtn" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>

  <el-row>
    <el-col :span="3" style="margin-bottom: 8px">
      <p class="pinformation">检测项目列表</p>
    </el-col>
  </el-row>
  <el-table
    id="jcxmGroupTable"
    :data="jcxmGroupList"
    height="620px"
    class="business"
    ref="jcxmGroupRef"
    v-loading="loading"
    border
    :highlight-current-row="highLightRow"
    @row-click="rowClick"
    row-key="mJId"
    @select="handleSelectionChange"
    :header-cell-class-name="cellClass"
  >
    <el-table-column
      type="selection"
      width="55"
      align="center"
      :selectable="selectable"
    />
    <el-table-column label="检测项目组别" align="left" width="150">
      <template #default="scope">
        <dict-tag
          :id="scope.row.mJId"
          :options="lims_jcxm_group"
          :value="scope.row.mJId"
          style="display: inline"
        />
      </template>
    </el-table-column>
    <el-table-column label="检测项目" align="center" prop="jcxmName" width="200">
      <template #default="scope">
        <span v-html="transformation(scope.row.jcxmName)"></span>
      </template>
    </el-table-column>
    <el-table-column label="是否求和" align="center" width="130">
      <template #default="scope">
        <el-select
          v-if="!scope.row.jcxmId"
          v-model="scope.row.isSum"
          placeholder="请选择"
          style="width: 100%"
          @change="autoSelected(scope.row)"
        >
          <el-option
            v-for="item in isSumData"
            :label="item.label"
            :key="item.value"
            :value="item.value"
          />
        </el-select>
      </template>
    </el-table-column>
    <el-table-column label="检测方法编号" align="center" prop="methodCode" width="200" />
    <el-table-column label="检测方法名称" align="center" prop="methodName" />
  </el-table>
</template>

<script setup>
import $ from "jquery";
import {
  queryJcxmGroupList,
  addSelectedJcxm,
  addSelectedJcxmList,
  addTaskJcxmGroupList,
  deleteSelectedJcxm,
  updateIsSum,
} from "@/api/contract/taskPoint";
import { nextTick } from "vue";
const { proxy } = getCurrentInstance();
const jcxmGroupList = ref([]); // 右侧检测项目列表搜索结果
const highLightRow = ref(true); // 表格选中高亮样式
const loading = ref(false);
const { lims_jcxm_group } = proxy.useShareDict("lims_jcxm_group");
const props = defineProps({
  params: {
    type: Object,
  },
  // 父组件中的方法
  handleSelectionChange: {
    type: Function,
  },
});
const isSumData = [
  {
    value: 0,
    label: "否",
  },
  {
    value: 1,
    label: "是",
  },
];
const data = reactive({
  jcxmForm: {
    isPackage: 0,
    isMethod: "0",
    isSum: "0",
  },
  queryParams: {},
});
const { queryParams, jcxmForm } = toRefs(data);
watch(
  () => props.params.isPackage,
  (val) => {
    if (val) {
      jcxmForm.value.isPackage = val;
    }
  }
);

watch(
  () => props.params.packageId,
  (val) => {
    if (val) {
      jcxmForm.value.packageId = val;
      jcxmForm.value.packageName = props.params.packageName;
    } else {
      delete jcxmForm.value.packageId;
      delete jcxmForm.value.packageName;
    }
  }
);

watch(
  () => props.params.isCollect,
  (val) => {
    if (val) {
      jcxmForm.value.isCollect = val;
    }
  }
);

// 对外暴露以下方法或变量
defineExpose({
  setFormParams,
  reselection,
});
function setFormParams(paramsForm) {
  if (!paramsForm.pointId || !paramsForm.pointJclbId) return;
  Object.assign(jcxmForm.value, paramsForm);
  queryParams.value.params = { pointId: paramsForm.pointId };
  queryParams.value.jclbId = paramsForm.pointJclbId;
  handleQuery();
}
// 获取检测项目列表数据
function handleQuery() {
  loading.value = true;
  queryJcxmGroupList(queryParams.value).then((res) => {
    jcxmGroupList.value = res.data;
    loading.value = false;
    // 是否默认勾选通过id判断
    nextTick(() => {
      jcxmGroupList.value.forEach((row) => {
        let children = row.children;
        if (row.params && row.params.cJId) {
          //全选
          proxy.$refs["jcxmGroupRef"].toggleRowSelection(row);
          return;
        }
        //如果上述if条件成立则子节点会自动选中所以不需要再次判断是否需要选中。
        children.forEach((row1) => {
          if (row1.params && row1.params.cJId && row1.groupId) {
            proxy.$refs["jcxmGroupRef"].toggleRowSelection(row1);
          }
        });
      });
    });
  });
}

function resetQuery() {
  proxy.resetForm("groupJcxmGroupRef");
  handleQuery();
}

const emit = defineEmits(["setJcxmCount", "pointMove"]);

function handleSelectionChange(selection, row) {
  if (
    jcxmForm.value.isPackage == 1 &&
    proxy.parseStrEmpty(jcxmForm.value.packageId).length == 0
  ) {
    proxy.$refs["jcxmGroupRef"].toggleRowSelection(row);
    proxy.$modal.msgError("分包公司不能为空！");
    return;
  }
  jcxmForm.value.mJId = row.mJId;
  //选中行的主键即任务检测项目的主键，根据此值判断当前操作是选中还是取消选中。
  let cJId;
  if (
    selection.filter((item) => {
      return item == row;
    }).length == 0
  ) {
    // if (row.params && row.params.cJId) {
    //当前操作是取消选中
    if (row.children) {
      cJId = "-9753" + row.mJId; //约定：-9753开头的为检测项目组id
    } else {
      cJId = row.params.cJId;
    }
    deleteSelectedJcxm(jcxmForm.value.pointId, cJId)
      .then((res) => {
        delete row.params;
        let data = {
          jcxmCount: res.data.jcxmCount,
          jcxmPCount: res.data.jcxmPCount,
        };
        emit("setJcxmCount", data);
        nextTick(() => {
          selection.forEach((item) => {
            let isChecked = !(
              item.mJId == row.mJId ||
              (item.groupId && item.groupId == row.mJId)
            );
            if (item.groupId) {
              proxy.$refs["jcxmGroupRef"].toggleRowSelection(item, isChecked);
            }
          });
        });
      })
      .catch(() => {
        delete row.params;
      });
  } else {
    let isSum = 0;
    let flag = true;
    let methodId;
    if (row.children) {
      isSum = row.isSum;
      jcxmForm.value.taskJcxmList = row.children.filter((item) => item.groupId);
      jcxmForm.value.taskJcxmList.find((item) => {
        const selectedMJIds = selection.map((m) => {
          return m.mJId;
        });
        if (selectedMJIds.length > 0) {
          if (selectedMJIds.indexOf(item.mJId) == -1) {
            return false;
          }
          if (!methodId) {
            methodId = item.methodId;
          } else if (methodId != item.methodId) {
            proxy.$modal.msgError("求和时当前检测项目组内的检测方法必须相同！");
            nextTick(() => {
              proxy.$refs["jcxmGroupRef"].toggleRowSelection(row, false);
            });
            flag = false;
            return true;
          }
        }
        item.isSum = row.isSum;
      });
      if (!flag) {
        return;
      }
      addSelectedJcxmList(jcxmForm.value)
        .then((res) => {
          let data = {
            jcxmCount: res.data.jcxmCount,
            jcxmPCount: res.data.jcxmPCount,
          };
          emit("setJcxmCount", data);
          const headerCheckbox = $("#jcxmGroupTable table thead tr label.el-checkbox")[0];
          if (jcxmForm.value.isPackage == 0)
            emit("pointMove", headerCheckbox, $("#openSelJcxmDialog"));
          else emit("pointMove", headerCheckbox, $("#openSelJcxmDialog1"));
          handleQuery();
        })
        .catch((e) => {
          selection.forEach((item) => {
            let isChecked = !(
              item.mJId == row.mJId ||
              (item.groupId && item.groupId == row.mJId)
            );
            if (item.groupId) {
              proxy.$refs["jcxmGroupRef"].toggleRowSelection(item, isChecked);
            }
          });
        });
      return;
    }
    isSum = isSumByChildren(row.groupId);
    selection
      .filter((item) => {
        return item.groupId && item.groupId == row.groupId;
      })
      .find((item) => {
        if (item.methodId) {
          if (!methodId) {
            methodId = item.methodId;
          } else if (methodId != item.methodId) {
            proxy.$modal.msgError("求和时当前检测项目组内的检测方法必须相同！");
            proxy.$refs["jcxmGroupRef"].toggleRowSelection(row, false);
            flag = false;
            return true;
          }
        }
      });
    if (!flag) {
      return;
    }
    //当前操作是选中
    Object.assign(jcxmForm.value, row);
    addSelectedJcxm(jcxmForm.value)
      .then((res) => {
        if (!row.params) {
          row.params = {};
        }
        row.params.cJId = res.data.cJId;
        nextTick(() => {
          selection.forEach((item) => {
            proxy.$refs["jcxmGroupRef"].toggleRowSelection(item, true);
            if (item.mJId == row.mJId) {
              let children = row.children;
              if (children) {
                children.forEach((item1) => {
                  proxy.$refs["jcxmGroupRef"].toggleRowSelection(item1, true);
                });
              }
            }
          });
        });
        let data = {
          jcxmCount: res.data.jcxmCount,
          jcxmPCount: res.data.jcxmPCount,
        };
        emit("setJcxmCount", data);
        let checkboxTd = $("#" + row.mJId)
          .parents("td")
          .prev();
        if (jcxmForm.value.isPackage == 0)
          emit("pointMove", checkboxTd[0], $("#openSelJcxmDialog"));
        else emit("pointMove", checkboxTd[0], $("#openSelJcxmDialog1"));
      })
      .catch((e) => {
        proxy.$refs["jcxmGroupRef"].toggleRowSelection(row, false);
      });
  }
}

function reselection() {
  handleQuery();
}

function rowClick() {
  highLightRow.value = true;
}
function transformation(row) {
  if (row) {
    const a = proxy.getSupAndSub(row);
    return a;
  }
}

function autoSelected(row) {
  const selection = proxy.$refs["jcxmGroupRef"].getSelectionRows();
  nextTick(() => {
    selection.forEach((item) => {
      proxy.$refs["jcxmGroupRef"].toggleRowSelection(item, true);
    });
  });
  jcxmGroupList.value.find((item) => {
    if (item.mJId && item.mJId == row.mJId) {
      if (item.children) {
        const selectedMJIds = selection.map((m) => {
          return m.mJId;
        });
        if (selectedMJIds.length > 0) {
          let methodId;
          for (const i in item.children) {
            const item1 = item.children[i];
            if (selectedMJIds.indexOf(item1.mJId) == -1) {
              continue;
            }
            if (!methodId) {
              methodId = item1.methodId;
            } else if (methodId != item1.methodId) {
              proxy.$modal.msgError("求和时当前检测项目组内的检测方法必须相同！");
              row.isSum = 0;
              return true;
            }
          }
        }
        handleUpdateIsSum(row.mJId, row.isSum);
        item.children.forEach((item1) => {
          item1.isSum = row.isSum;
        });
      }
      return true;
    }
  });
}

function handleUpdateIsSum(groupId, isSum) {
  const data = {
    pointId: queryParams.value.params.pointId,
    groupId: groupId,
    isSum: isSum,
  };
  updateIsSum(data).then();
}

function isSumByChildren(mJId) {
  let isSum = 0;
  jcxmGroupList.value.find((item) => {
    if (item.mJId && item.mJId == mJId) {
      isSum = item.isSum;
      return true;
    }
  });
  return isSum;
}
function cellClass(row) {
  if (row.columnIndex === 0) {
    return "DisableSelection";
  }
}

function selectable(row) {
  return true;
  // if (row.groupId || row.children) {
  //   return true;
  // } else {
  //   return false;
  // }
}
</script>

<style>
.el-table__header .DisableSelection .cell {
  visibility: hidden;
}
</style>
